package com.baizw.cultivation.module.admin.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.baizw.cultivation.common.response.ResultBean;
import com.baizw.cultivation.module.admin.entity.vo.LoginFormVO;
import com.baizw.cultivation.module.admin.service.UserService;
import com.baizw.cultivation.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;

/**
 * 用户授权接口
 *
 * @author 剧终1204
 * @version V1.0
 * @date 2020年04月29日 11:18:37
 */
@Slf4j
@Validated
@RestController
@Api(tags = "用户授权接口")
@RequestMapping("/api/auth")
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("/login")
    @ApiOperation("用户登录接口")
    public ResultBean login(@Valid @RequestBody LoginFormVO loginForm) {
        return userService.authLogin(loginForm);
    }

    @GetMapping(value = "/captcha/{uuid}", produces = "image/png")
    @ApiOperation("获取验证码")
    public void getCaptcha(@PathVariable String uuid, HttpServletResponse response) {
        try {
            CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(112, 40);
            String code = captcha.getCode();
            // 将验证码放入缓存，有效期1分钟
            redisUtil.set(uuid, code, 60);
            log.info("UUID: {} ----验证码: {}", uuid, code);
            @Cleanup ServletOutputStream outputStream = response.getOutputStream();
            captcha.write(outputStream);
        } catch (IOException e) {
            log.error("验证码获取失败", e);
        }
    }

    @GetMapping("/logout")
    @ApiOperation("用户退出登录")
    public ResultBean logout(@PathVariable String token) {
        return ResultBean.isTrue(redisUtil.removeToken(token));
    }
}
